const http = require('http');
const fs = require('fs');
const path = require('path');
const dgram = require('dgram');

const PORT = 3000;

// 创建HTTP服务器
const server = http.createServer((req, res) => {
    if (req.method === 'GET' && req.url === '/') {
        // 提供index.html文件
        fs.readFile(path.join(__dirname, '../index.html'), 'utf8', (err, data) => {
            if (err) {
                res.writeHead(500);
                res.end('Error loading HTML file');
                return;
            }
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end(data);
        });
    } else if (req.method === 'POST' && req.url === '/submit-configuration') {
        // 处理表单提交
        let body = '';
        req.on('data', chunk => {
            body += chunk.toString();
        });
        req.on('end', () => {
            const configuration = JSON.parse(body);

            // 发送UDP数据
            const udpClient = dgram.createSocket('udp4');
            const udpMessage = Buffer.from(JSON.stringify(configuration));
            udpClient.send(udpMessage, 0, udpMessage.length, 4950, 'localhost', (err) => {
                if (err) {
                    console.error('UDP send error:', err);
                    res.writeHead(500);
                    res.end('Failed to send UDP message');
                } else {
                    res.writeHead(200);
                    res.end('Configuration sent via UDP');
                }
                udpClient.close();
            });
        });
    } else {
        res.writeHead(404);
        res.end('Not Found');
    }
});

// 启动服务器
server.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});
